import React, { useEffect } from 'react';
import { RouterProvider } from 'react-router-dom';
import { router } from './routes';
import './App.css';
import { authService } from './services/auth';
import { isTokenExpiringSoon } from './utils/auth';

// 自动刷新Token的自定义Hook
function useAutoRefreshToken() {
  useEffect(() => {
    // 初始加载时立即检查token
    const checkAndRefreshToken = async () => {
      const token = localStorage.getItem('token');
      if (token && isTokenExpiringSoon(token)) {
        try {
          const res = await authService.refreshToken();
          if (res.data.code === 200) {
            localStorage.setItem('token', res.data.data.token);
          } else {
            handleLogout();
          }
        } catch {
          handleLogout();
        }
      }
    };

    // 处理登出逻辑
    const handleLogout = () => {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    };

    // 立即执行一次检查
    checkAndRefreshToken();

    // 设置定时器，每分钟检查一次
    const interval = setInterval(checkAndRefreshToken, 60 * 1000);
    return () => clearInterval(interval);
  }, []);
}

function App() {
  useAutoRefreshToken(); // 启用自动刷新token
  return (
    <div className="App">
      <RouterProvider router={router} />
    </div>
  );
}

export default App;
